<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getDeptpartments">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

    <!--列表-->
		<el-table :data="rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
      <el-table-column prop="sn" label="部门编号" width="140" sortable>
      </el-table-column>
			<el-table-column prop="name" label="部门名称" width="140" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="140" sortable>
        <template scope="scope">
          <span v-if="scope.row.state==0" style="color: green">启用</span>
          <span v-else-if="scope.row.state==-1" style="color: red">禁用</span>
          <span v-else style="color: #8c939d">未知</span>
        </template>
			</el-table-column>
			<el-table-column prop="dirPath" label="上级分类层级id" width="200" sortable>
			</el-table-column>
			<el-table-column prop="manager.username" label="管理员" width="120" sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="上级部门" min-width="180" sortable>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" v-perm="'dept:deleteById'" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :pageSize="pageSize"
                     :total="total"
                     :currentPage="currentPage"
                     style="float:right;">
			</el-pagination>
		</el-col>
      <!--
        editFormVisible:编辑框是否显示
      -->



		<!--编辑界面-->
		<el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">

				<el-form-item label="部门名称" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>

        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>

				<el-form-item label="状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="0">正常</el-radio>
						<el-radio class="radio" :label="-1">禁用</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item  label="管理员">
          <!--
              item in employees : 要遍历的数组和每次遍历的对象
              :key  唯一键 绑定id
              :label： 下拉框最后确定的选项显示的样子
              :value  最终要传递的值
                注意要是最终要传递的是一个对象  就必须要加上 value-key="id" 这个
          -->
            <el-select v-model="editForm.manager" value-key="id" placeholder="请选择">
              <el-option
                  v-for="item in employees"
                  :key="item.id"
                  :label="item.username"
                  :value="item">
                <span style="float: left">{{ item.username }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
              </el-option>
            </el-select>
				</el-form-item>

        <el-form-item label="上级部门">
          <!--
            :options  绑定模型层的数据
            :props { 数据里面的对象们
                value: 最后传递的值
                label: 显示的属性
                }
          -->
            <el-cascader v-model="editForm.parent"
                :options="DeptTree"
                :props="{
                  checkStrictly: true ,
                  value:'id',
                  label:'name'
                }"
                clearable></el-cascader>
        </el-form-item>
			</el-form>

			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getDeptpartmentListPage, removeDeptpartment, batchRemoveDeptpartment, editDeptpartment, addDeptpartment } from '../../api/api';

	export default {
		data() {
			return {
        title:'',
				filters: {
          keyword: ''
				},
				rows: [],
        employees:[],
        //无限极数据，上级部门
        DeptTree:[],
				total: 0,
        currentPage: 1,
        pageSize:5,
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
        //editFormRules 设置（相当于正则表达式）
				editFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//编辑界面数据
				editForm: {
          id: null,
          name: '',
          sn: '',
          dirPath:'',
          state: 0,
          manager_id: null,
          manager: null,
          parent: null,
          parent_id:null
				},

			}
		},
		methods: {
		  //获得上级部门的无线级树
		  getDeptTree(){
		    this.$http.get("/dept/tree")
         .then(result=>{
           this.DeptTree=result.data;
         })
      },

			//性别显示转换
		/*	formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},*/
      //点击页码触发事件
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDeptpartments();
			},
      //给管理员回显数据
      getEmployees(){
			  this.$http.get("/emp")
          .then(result=>{
            result=result.data;
            this.employees=result;
          })
          .catch(result=>{
            this.$message({
              message: '网络繁忙，请稍后再试',
              type: 'error'
            });
          })
      },


			//获取部门列表  也是高级查询的方法
			getDeptpartments() {
				let para = {
          currentPage: this.currentPage,
          keyword: this.filters.keyword
				};
				this.listLoading = true;
        this.$http.post("/dept",para)
          .then(result => {
            this.listLoading = false;
            result=result.data;
            this.total=result.total;
            this.rows=result.data;
          })
          .catch(result=>{
            //这一步基本上不会走
            this.$message({
              message: '网络繁忙，请稍后再试',
              type: 'error'
            });
          })


				//NProgress.start();
			/*	getDeptpartmentListPage(para).then((res) => {
					this.total = res.data.total;
					this.deptpartments = res.data.deptpartments;
					this.listLoading = false;
					//NProgress.done();
				});*/
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '温馨提示', {
					type: 'warning'
				}).then(() => {//确定
					this.listLoading = true;
					//NProgress.start();
					/*let para = { id: row.id };*/
					this.$http.delete("/dept/"+row.id)
            .then(result=>{
              result=result.data;
              if(result.success){
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
              }else{
                  this.$message({
                    message: result.message,
                    type: 'error'
                  });
              }
              this.currentPage=1;
              this.getDeptpartments();
              //不用关闭忙等框 getDeptpartments 调用这个方法的时候里面有关闭忙等框
            })
            .catch(result=>{
              this.currentPage=1;
              this.getDeptpartments();
            })

				}).catch(() => {
          //取消
				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
			  this.title="编辑";
			  //加载上级部门数据
			  this.getDeptTree();
			  //弹出模态框
				this.editFormVisible = true;
				//数据回显 克隆一个在进行操作(双向绑定数据改变列表的数据也会有变化)
				this.editForm = Object.assign({}, row);

         //   "/2/5/10"   this.editForm.dirPath 2,5才是这个数据的父类以及祖类  10是自己的id
        var arr = this.editForm.dirPath.split("/");  //    "/2/5/10"  ===》  ["","2","5","10"]
        var dirPath=[];
        for (let i = 1; i < arr.length-1; i++) {
          //把字符串数字 转变成int类型  parseInt
          dirPath[i-1]=parseInt(arr[i]);
        }
         // dirPath ===>  [2,5]  编辑框回显的数据双向绑定的是parent对象 所以回显要改变parent的值 只显示父类以及祖类
        this.editForm.parent=dirPath;

			},
			//显示新增界面
			handleAdd: function () {
        this.title="新增";

        //加载上级部门数据
        this.getDeptTree();
        this.editFormVisible = true; //显示编辑页面  公用一个页面
        //初始化新增页面里面的值
				this.editForm = {
          id: null,
          name: '',
          sn: '',
          dirPath:'',
          state: 0,
          manager_id: null,
          manager: null,
          parent: null,
          parent_id:null
        };
			},
			//编辑
			editSubmit: function () {
			  //this.$refs.editForm.validate((valid)  validate 帮我们校验正则表达式
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
						  //提交按钮忙等框
							this.editLoading = true;
							//NProgress.start();
              this.editForm.manager_id=this.editForm.manager.id;
							let para = Object.assign({}, this.editForm);

              //对parent对象进行修改 ，才能传到后端去
              if(para.parent){//  [1,34]  这个得到的是父类以及父类上面的id
                para.parent_id=para.parent[para.parent.length-1];// 得到的是父类的id  34
                para.parent={"id":para.parent[para.parent.length-1]} //{id:34}  必须要有这个转，因为传递后端类型不一样要报错
              }

							this.$http.put("/dept",para)
                .then(result=>{
                  result=result.data;
                  if(result.success){
                    //成功关闭模态框
                    this.editFormVisible = false;
                    this.$message({
                      message: '操作成功',
                      type: 'success'
                    });
                  }else{
                    this.$message({
                      message: '操作失败',
                      type: 'error'
                    });
                  }
                  //关闭提交按钮忙等
                  this.editLoading = false;

                  /*this.currentPage=1;*/
                  this.getDeptpartments();

                })
                .catch(result=>{
                  this.editLoading = false;
                  this.$message({
                    message: '网络繁忙，稍后再试',
                    type: 'error'
                  });

                })

						});
					}
				});
			},
			//新增
/*

*/
    //点击复选框 里面的id都会传到这个数组上面
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id).toString();
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { ids: ids };
          this.$http.patch("/dept",para)
            .then(result=>{
              result=result.data;
              if(result.success){
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
              }else{
                this.$message({
                  message: '删除失败',
                  type: 'error'
                });
              }
              this.currentPage=1;
              this.getDeptpartments();
            })
            .catch(result=>{
              this.$message({
                message: '网络繁忙，请稍后再试',
                type: 'error'
              });
              this.currentPage=1;
              this.getDeptpartments();
            })
				}).catch(() => {

				});
			}
		},
		mounted() {
			this.getDeptpartments();
			this.getEmployees();
		}
	}

</script>

<style scoped>

</style>